package cn.edu.zjicm.wordsnet_d.download;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface.OnCancelListener;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.data.VoicePack;
import cn.edu.zjicm.wordsnet_d.datapersistent.FileManager;
import cn.edu.zjicm.wordsnet_d.net.Client;
import cn.edu.zjicm.wordsnet_d.util.LogUtil;
import cn.edu.zjicm.wordsnet_d.util.StringUtil;
import cn.edu.zjicm.wordsnet_d.util.VoicePackViewHolder;
import cn.edu.zjicm.wordsnet_d.view.MyDialog;

public class DownloadVoicePackManager {

	private static Map<String, DownloadVoicePackManager> map = new HashMap<String, DownloadVoicePackManager>();
	private static int countOfDownloadingThread = 0; // 正在下载的线程数

	private Context mContext;
	private Handler handler; // 用来指示活动，下载已完成
	private boolean inListView = false; // 是否用于文章列表的下载

	private String name;
	private VoicePack mVoicePack;

	private DownloadArticleThread mArticleThread;

	public static DownloadVoicePackManager getInstance(Context context, String name, Handler handler, boolean inListView) {
		DownloadVoicePackManager mInstance;
		if (map.get(name) != null) {
			mInstance = map.get(name);
			mInstance.setInListView(inListView);
			if (inListView)
				mInstance.setHandler(mInstance.mHandlerInListView);
			else
				mInstance.setHandler(handler);
		} else {
			mInstance = new DownloadVoicePackManager(context, name, handler, inListView);
			if (inListView)
				mInstance.setHandler(mInstance.mHandlerInListView);
			map.put(name, mInstance);
		}
		return mInstance;
	}

	public static boolean isDownloadManagerExist(String name) {
		DownloadVoicePackManager downloadManager = map.get(name);
		if (downloadManager != null /* && downloadManager.getIsDownloading() */)
			return true;
		else
			return false;
	}

	public static void removeDownloadManager(String name) {
		DownloadVoicePackManager.map.remove(name);
	}

	// 如果还有没开始下载的任务，选择一个开始下载
	public static void startAnotherDownloadTask() {
		Set<String> set = map.keySet();

		Iterator<String> it = set.iterator();
		while (it.hasNext()) {
			String key = it.next();
			DownloadVoicePackManager downloadManager = map.get(key);
			if (!downloadManager.getIsDownloading() && downloadManager.inListView == false) {
				downloadManager.startToDownload();
				return;
			}
		}

		it = set.iterator();
		while (it.hasNext()) {
			String key = it.next();
			DownloadVoicePackManager downloadManager = map.get(key);
			if (!downloadManager.getIsDownloading() && downloadManager.inListView == true) {
				downloadManager.startToDownload();
				return;
			}
		}
	}

	private DownloadVoicePackManager(Context mContext, String name, Handler handler, boolean inListView) {
		this.name = name;
		this.mContext = mContext;
		this.handler = handler;
		this.inListView = inListView;
		this.mVoicePack = VoicePack.getVoicePack(name);
		// LogUtil.e("articleid", "文章名称是" + article_id);
	}

	private void setHandler(Handler handler) {
		this.handler = handler;
	}

	public boolean isInListView() {
		return inListView;
	}

	public void setInListView(boolean inListView) {
		this.inListView = inListView;
	}

	// 非inListView,需马上下载； inListView需要等到其他下载线程完后才开始下载
	public void startToDownload() {

		if (!inListView || (inListView && DownloadVoicePackManager.countOfDownloadingThread == 0)) {
			if (!getIsDownloading()) {
				startDownloading();
			}
		}
		// if (DownloadVoicePackManager.countOfDownloadingThread == 0) {
		// if (!getIsDownloading()) {
		// startDownloading();
		// }
		// }
	}

	public void startDownloading() {
		DownloadVoicePackManager.countOfDownloadingThread++;
		mArticleThread = new DownloadArticleThread();
		mArticleThread.start();
	}

	public boolean getIsDownloading() {
		if (mArticleThread != null)
			return mArticleThread.isDownloading;
		else
			return false;
	}

	// 是否需要下载语音包
	public static boolean checkDownload(VoicePack voicePack) {
		if (!FileManager.isZipFileExist(voicePack, false)) {
			return true;
		} else {
			return false;
		}
	}

	/* 显示有移动网络，无wifi */
	public static void showMobileConnectedDialog(final Context context, OnCancelListener onclickListener, final boolean finishActivity) {
		View view = LayoutInflater.from(context).inflate(R.layout.view_check_download_dialog, null);
		TextView tv1 = (TextView) view.findViewById(R.id.dialog_tv1);
		TextView tv2 = (TextView) view.findViewById(R.id.dialog_tv2);
		Button sureBtn = (Button) view.findViewById(R.id.sure_download_btn);
		Button cancelBtn = (Button) view.findViewById(R.id.cancel_download_btn);
		tv1.setText("提示");
		String text2 = "您的手机正在使用数据流量，下载语音包可能会耗费较多流量，确认继续吗？";
		tv2.setText(StringUtil.ToDBC(text2));
		final MyDialog dialog = new MyDialog(context, view, R.style.mydialog, false);
		dialog.setOnCancelListener(onclickListener);
		sureBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
			}
		});
		cancelBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
				if (finishActivity)
					((Activity) context).finish();
			}
		});
		dialog.show();
	}

	VoicePackViewHolder holder;

	public void showDownloadingLayout(VoicePackViewHolder holder, VoicePack voicePack) {
		this.holder = holder;
		this.mVoicePack = voicePack;
	}

	/* 下载完成 */
	public void downloadComplete() {

		Message msg = new Message();
		msg.what = SUCCESS;
		msg.obj = mVoicePack.getName();
		if (handler != null)
			handler.sendMessage(msg); // 提示活动，下载已完成

		DownloadVoicePackManager.removeDownloadManager(mVoicePack.getName()); // 下载完从map中删除
		DownloadVoicePackManager.startAnotherDownloadTask(); // 启动一个未开始的下载任务
	}

	/**
	 * 当正在下载时，网络断开所进行的操作
	 */
	public void downloadFailed() {
		Message msg = new Message();
		msg.what = FAIL;
		msg.obj = mVoicePack.getName();
		if (handler != null)
			handler.sendMessage(msg);

		DownloadVoicePackManager.removeDownloadManager(mVoicePack.getName()); // 下载完从map中删除
		DownloadVoicePackManager.startAnotherDownloadTask(); // 启动一个未开始的下载任务
	}

	public void updateDownloadNum(int progress, String str) {
		Message msg = new Message();
		msg.what = UPDATE;
		msg.obj = str;
		msg.arg1 = progress;
		if (handler != null)
			handler.sendMessage(msg);
	}

	public static final int UPDATE = 0;
	public static final int SUCCESS = 1;
	public static final int FAIL = 2;

	Handler mHandlerInListView = new DownloadArticleHandlerInListView();

	public class DownloadArticleHandlerInListView extends Handler {

		public void handleMessage(android.os.Message msg) {
			String packName = null;
			switch (msg.what) {
			case UPDATE:
				// int progress = (Integer) msg.obj;
				if (holder != null)
					holder.roundProgressBar.setProgress(msg.arg1);
				break;
			case SUCCESS:
				packName = (String) msg.obj;
				Toast.makeText(mContext, packName + "下载成功", Toast.LENGTH_SHORT).show();
				if (holder != null) {
					holder.downloadFlipper.setDisplayedChild(0);
					holder.download_state.setImageResource(R.drawable.download_complete);
				}
				break;
			case FAIL:
				packName = (String) msg.obj;
				Toast.makeText(mContext, packName + "下载失败，请确保网络连接正常，并保证sd卡有足够的可用空间！", Toast.LENGTH_SHORT).show();
				// Toast.makeText(mContext, mVoicePack.getName() + "下载失败，请稍后再试",
				// Toast.LENGTH_SHORT).show();
				if (holder != null)
					holder.downloadFlipper.setDisplayedChild(0);
				break;
			}
		};
	};

	public class DownloadArticleThread extends Thread {

		private String savePath;
		private String path;

		public boolean isDownloading = false;

		public DownloadArticleThread() {
			init();
		}

		private void init() {
			path = Client.BASE_VOICE_URL + mVoicePack.getDownloadFileName();
			savePath = FileManager.getZipFilePath(mVoicePack) + ".nc";
		}

		@Override
		public void run() {
			File file = new File(FileManager.DOWNLOAD_PATH);

			File parentFile = new File(FileManager.DEFAULT_SAVE_PATH);
			if (!parentFile.exists()) {
				LogUtil.d("parentFile文件夹不存在");
				parentFile.mkdirs();
			}

			if (!file.exists()) {
				LogUtil.d("文件夹不存在");
				file.mkdirs();

				if (file.exists()) {
					LogUtil.d("文件夹创建成功");
				}
			}

			download();
		}

		private void download() {
			isDownloading = true;
			InputStream inputStream = null;
			OutputStream outputStream = null;
			int allSize, nowSize = 0;
			try {
				URL url = new URL(path);
				HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
				urlConnection.setConnectTimeout(5000);
				urlConnection.setReadTimeout(10000);
				urlConnection.connect();
				inputStream = urlConnection.getInputStream();

				allSize = urlConnection.getContentLength();// 根据响应获取文件大小
				if (allSize <= 0) { // 获取内容长度为0
					throw new NoContentException("无法获知文件大小 ");
				}
				if (inputStream == null /* || urlConnection.getURL() != url */) { // 没有下载流
					throw new FileNotFoundException("没有下载流");
				}
				int responseCode = urlConnection.getResponseCode();
				if (responseCode == HttpURLConnection.HTTP_OK) {
					File file1 = new File(savePath);
					outputStream = new BufferedOutputStream(new FileOutputStream(file1)); // 默认覆盖原文件
					byte[] buffer = new byte[2 * 1024];
					int size;
					while ((size = inputStream.read(buffer)) != -1) {
						outputStream.write(buffer, 0, size); // 防止流写入问题,原来使用outputStream.write(buffer);
						nowSize += size;
						int progress = 0;
						if (allSize == 0)
							progress = 0;
						else {

							DownloadManager.allHasDownloadSize += size;
							if (inListView) {
								progress = (int) (1.0 * nowSize / allSize * 100);
							} else {
								progress = (int) (1.0 * DownloadManager.allHasDownloadSize / DownloadManager.allZipSize * 100);
							}

//							LogUtil.d("progress:" + progress + ",hasSize:" + DownloadManager1.allHasDownloadSize + ",allSize:" + DownloadManager1.allZipSize + ",nowSize=" + nowSize);
						}

						StringBuilder sb = new StringBuilder();
						sb.append(DownloadManager.allHasDownloadSize / 1024).append("KB/").append(DownloadManager.allZipSize / 1024).append("KB").append(":").append(mVoicePack.getName());
						updateDownloadNum(progress, sb.toString());
					}
					outputStream.flush();

					if (isDownloading && (nowSize / 1024 / 1024 >= (int) mVoicePack.getShowSize())) {
						String downloadedVoiceFilePath = FileManager.renameDownloadCompelateFile(new File(savePath));
						FileManager.unZipDownloadedVoiceFile(new File(downloadedVoiceFilePath));

						downloadFinish();
						downloadComplete();
					} else {
						LogUtil.e("返回不是200");
						downloadFail();
					}
				} else {
					LogUtil.e("返回不是200");
					downloadFail();
				}
			} catch (FileNotFoundException e) {
				// 这里还没确定处理结果
				LogUtil.e("FileNotFoundException" + e.getMessage() + "：下载" + mVoicePack.getName() + ":" + path + "失败");
				downloadFail();
			} catch (NoContentException e) {
				LogUtil.e("NoContentException" + e.toString());
				downloadFail();
			} catch (UnknownHostException e) {
				LogUtil.e("UnknownHostException" + e.getMessage() + "：下载" + mVoicePack.getName() + ":" + path + "失败");
				downloadFail();
			} catch (SocketException e) {
				LogUtil.e("SocketException" + e.getMessage() + "：下载" + mVoicePack.getName() + ":" + path + "失败");
				downloadFail();
			} catch (MalformedURLException e) {
				LogUtil.e("MalformedURLException" + e.getMessage() + "");
				downloadFail();
			} catch (IOException e) {
				LogUtil.e("IOException " + e.getMessage() + "：下载" + mVoicePack.getName() + ":" + path + "失败");
				downloadFail();
			} catch (Exception e) {
				LogUtil.e("Exception" + e.getMessage() + "");
				downloadFail();
			} finally {
				try {
					if (outputStream != null) {
						outputStream.close();
						outputStream = null;
					}
					if (inputStream != null) {
						inputStream.close();
						inputStream = null;
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		public void downloadFail() {
			downloadFinish();
			downloadFailed();
			try {
				File file = new File(FileManager.getZipFilePath(mVoicePack));
				if (file.exists())
					file.delete();
			} catch (Exception e) {
				LogUtil.e("删除语音包失败" + e);
			}
		}

		public void downloadFinish() {
			DownloadVoicePackManager.countOfDownloadingThread--;
			LogUtil.e("正在下载的线程 由" + (DownloadVoicePackManager.countOfDownloadingThread + 1) + "个变为" + DownloadVoicePackManager.countOfDownloadingThread + "个");
			isDownloading = false;
		}
	}

}

// /* 显示未联网 */
// public static void showBadNetworkDialog(final Context context, final boolean
// finishActivity) {
// View view =
// LayoutInflater.from(context).inflate(R.layout.view_check_download_dialog,
// null);
// final MyDialog dialog = new MyDialog(context, view, R.style.mydialog,false);
// TextView tv1 = (TextView) view.findViewById(R.id.dialog_tv1);
// TextView tv2 = (TextView) view.findViewById(R.id.dialog_tv2);
// TextView verticalDivider = (TextView)
// view.findViewById(R.id.vertical_divider);
// Button sureBtn = (Button) view.findViewById(R.id.sure_download_btn);
// Button cancelBtn = (Button) view.findViewById(R.id.cancel_download_btn);
// tv1.setText("未联网，无法继续学习");
// String text2 = "请您在联网状态下，在文章列表中下载文章。下载后，可离线学习。";
// sureBtn.setVisibility(View.GONE);
// verticalDivider.setVisibility(View.GONE);
// cancelBtn.setBackgroundResource(R.drawable.rect_bg_down_selector);
// cancelBtn.setText("确认");
// cancelBtn.setOnClickListener(new OnClickListener() {
//
// @Override
// public void onClick(View v) {
// dialog.cancel();
// if (finishActivity)
// ((Activity) context).finish();
// }
// });
// dialog.show();
// }
//
